//
//  NewDeviceViewController.m
//  YSSmartHome
//
//  Created by yanghao on 2016/12/30.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "NewDeviceViewController.h"
#import "NewDeviceCell.h"
#import "NotAddedDev.h"
#import "DataManager.h"
#import "MQTTSessionManager.h"
#import "GlobalConst.h"

static NSString* const NewDeviceCellIdentifier = @"NewDeviceCellIdentifier";
@interface NewDeviceViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
DataManagerRefreshDelegate
>
@property (nonatomic, strong)UITableView* m_tableView;
@property (nonatomic, strong)UIButton* m_btnDelete;
@property (nonatomic, strong)UIButton* m_btnAdd;
@property (nonatomic, strong)NSMutableArray* m_datasource;
@property (nonatomic, strong)NSLock* m_lock;
@end

@implementation NewDeviceViewController
- (void)dealloc
{
    [kDataManager removeNewJoinRefreshDelegate:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.m_datasource = [NSMutableArray array];
    [kDataManager addNewJoinRefreshDelegate:self];
    [kDataManager newJoinDevCallBack];
}

- (void)setupUI
{
    self.navigationItem.title = @"发现新设备";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"全选" style:UIBarButtonItemStyleDone target:self action:@selector(allSelected)];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self.view addSubview:self.m_tableView];
    [self.m_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.trailing.leading.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(kIphoneSize_Height(-50));
    }];
    [self.view addSubview:self.m_btnDelete];
    [self.view addSubview:self.m_btnAdd];
    [self.m_btnDelete mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_tableView.bottom);
        make.leading.bottom.equalTo(self.view);
        make.width.equalTo(self.view).multipliedBy(0.5);
        
    }];
    [self.m_btnAdd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(self.m_btnDelete);
        make.leading.equalTo(self.m_btnDelete.trailing);
        make.trailing.equalTo(self.view);
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 
- (void)newJoinRefresh:(DataManager* __nonnull)manager
{
    @synchronized (self) {
        NSMutableArray* newJoinDevs = [NSMutableArray array];
        for (int i = 0; i < manager.joinDevListenList.count; i++) {
            NotAddedDev* notAddDev = [[NotAddedDev alloc]init];
            notAddDev.title = [NSString stringWithFormat:@"新设备%zd",i];
            notAddDev.luid = [[manager.joinDevListenList objectAtIndex:i] longLongValue];
            [newJoinDevs addObject:notAddDev];
        }
        self.m_datasource = newJoinDevs;
    }
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        if (!strongSelf) {
            return ;
        }
        [strongSelf.m_tableView reloadData];
    });
}
#pragma mark - UITableViewDatasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.m_datasource.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewDeviceCell* cell = [tableView dequeueReusableCellWithIdentifier:NewDeviceCellIdentifier];
    cell.devmode = self.m_datasource[indexPath.row];
    debugLogInfo(@"devmode = %zd",cell.devmode.luid);
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NotAddedDev* notAddDev =  self.m_datasource[indexPath.row];
    notAddDev.isSelect = !notAddDev.isSelect;
    [self.m_tableView reloadData];
}
- (NSString* )tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"请对以下新设备进行操作";
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

#pragma mark - event response

- (void)allSelected
{
    [self.m_datasource enumerateObjectsUsingBlock:^(NotAddedDev*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.isSelect = true;
        
    }];
    [self.m_tableView reloadData];
}

- (void)btnTapped:(UIButton*)button
{
    NSMutableArray* notAddDevs = [NSMutableArray array];
    for (NotAddedDev* notAddDev in self.m_datasource)
    {
        if (notAddDev.isSelect)
        {
            [notAddDevs addObject:notAddDev];
        }
    }
    if (button == self.m_btnAdd)
    {
        for (NotAddedDev* notAddDev in notAddDevs)
        {
            NSMutableArray* array  = [NSMutableArray array];
            XAITYPEAPSN apsn = kMQTTSessionManager.currentUser.currentBindApsn;
            XAITLV* tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
            [array addObject:tlv];
            XAITYPELUID luid = notAddDev.luid;
            tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&luid length:sizeof(luid)];
            [array addObject:tlv];
            
            NSError* error = [kMQTTSessionManager.xai sendCMD:0x07 toApsn:apsn toLuid:kGATEWAYLUID datas:array];
            if (error.code == 0)
            {
                debugLogInfo(@"添加新设备成功");
            }
            else
            {
                debugLogInfo(@"添加新设备失败%@",error.localizedDescription);
            }
            [kDataManager deleteJoinDev:@(notAddDev.luid)];
            [ kDataManager newJoinDevCallBack];
        }
    }
    else if (button == self.m_btnDelete)
    {
        [self.m_datasource removeObjectsInArray:notAddDevs];
    }
    [self.m_tableView reloadData];
}
#pragma mark - getters and setters 

- (UITableView *)m_tableView
{
    if (!_m_tableView) {
        _m_tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _m_tableView.rowHeight = kIphoneSize_Height(55);
        _m_tableView.showsVerticalScrollIndicator = NO;
        _m_tableView.showsHorizontalScrollIndicator = NO;
        _m_tableView.delegate = self;
        _m_tableView.dataSource = self;
        [_m_tableView registerClass:[NewDeviceCell class] forCellReuseIdentifier:NewDeviceCellIdentifier];
    }
    return _m_tableView;
}
- (UIButton *)m_btnDelete
{
    if (!_m_btnDelete) {
        _m_btnDelete = [UIButton buttonWithType:UIButtonTypeCustom];
        [_m_btnDelete setTitle:@"删除" forState:UIControlStateNormal];
        [_m_btnDelete setTitleColor:RGBColor(51, 51, 51) forState:UIControlStateNormal];
        _m_btnDelete.titleLabel.font = [UIFont systemFontOfSize:17];
        _m_btnDelete.backgroundColor = [UIColor whiteColor];
        [_m_btnDelete addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _m_btnDelete;
}
- (UIButton *)m_btnAdd
{
    if (!_m_btnAdd)
    {
        _m_btnAdd = [UIButton buttonWithType:UIButtonTypeCustom];
        [_m_btnAdd setTitle:@"添加" forState:UIControlStateNormal];
        [_m_btnAdd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _m_btnAdd.titleLabel.font = [UIFont systemFontOfSize:17];
        _m_btnAdd.backgroundColor = kGlobalRedColor;
        [_m_btnAdd addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _m_btnAdd;
}
@end
